package controllers;

import helpers.IdUniqueHelper;
import helpers.StringHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.UserModel;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import debugs.UserDebug;

import entities.User;

public class RegisterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		if (request.getUserPrincipal() == null) {
			UserService userService = UserServiceFactory.getUserService();
			String thisURL = request.getRequestURI();
			String url = userService.createLoginURL(thisURL);
			
			response.sendRedirect(url);
			return;
		} else {
			String username = request.getUserPrincipal().getName();
			UserModel userModel = UserModel.getInstance();
			User user = userModel.getByUsername(username);
			if (user == null) {
				String name = StringHelper.getNameFromEmail(username);
				user = new User();
				user.setId(IdUniqueHelper.getId());
				user.setUsername(username);
				user.setName(name);
				
				userModel.insert(user);
			}
			
			response.sendRedirect("/");
			return;
		}
	}
}
